package spike.s001.builders.map.builders.serivice;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.*;

/**
 * Created by ylyang on 29/03/2017.
 */
public class PeopleBuilderWithMap {
    private static Logger logger = Logger.getLogger(PeopleBuilderWithMap.class);

    Map<String, Object> o = new HashMap<>();

    public PeopleBuilderWithMap() {
        o.put("NAME", UUID.randomUUID());
        o.put("AGE", (new Random()).nextInt(100));
        o.put("GENDER", randomFrom(new String[]{"Man", "Woman"}));
        o.put("ROLE", randomFrom(new String[]{"Dev", "BA", "QA", "RM", ""}));
    }

    public PeopleBuilderWithMap name(String name) {
        o.put("NAME", name);

        return this;
    }

    public PeopleBuilderWithMap age(int age) {
        o.put("AGE", age);

        return this;
    }

    public PeopleBuilderWithMap gender(String gender) {
        o.put("GENDER", gender);

        return this;
    }

    public PeopleBuilderWithMap role(String role) {
        o.put("ROLE", role);

        return this;
    }

    public void build(JdbcTemplate jdbcTemplate) {
        List<String> columns = new ArrayList<>();
        List<Object> values = new ArrayList<>();
        List<String> questionMarks = new ArrayList<>();

        for (Map.Entry<String, Object> entry : o.entrySet()) {
            if (entry.getValue() != null) {
                columns.add(entry.getKey());
                values.add(entry.getValue());
                questionMarks.add("?");
            }
        }

        String sqlLine = String.format("INSERT INTO PEOPLE(%s) VALUES(%s)",
                String.join(",", columns),
                String.join(",", questionMarks)
        );

        jdbcTemplate.update(sqlLine, values.toArray());

        logger.info(sqlLine + " --> OK");
    }

    private static String randomFrom(String[] a) {
        int x = (new Random()).nextInt(a.length);
        return a[x];
    }
}
